#!/bin/env python3

import sys
from PyPDF2 import PdfFileReader, PdfFileWriter


def split_pdf(in_file, out_file, start_page, end_page):
    pdfFileWriter = PdfFileWriter()

    pdfFileReader = PdfFileReader(in_file) 
    # 文档总页数
    if not end_page:
        end_page = pdfFileReader.getNumPages()

    # 分割文档：从第X页到Y页，输出到一个新的文件中
    for index in range(start_page, end_page):
        pageObj = pdfFileReader.getPage(index)
        pdfFileWriter.addPage(pageObj)
    # 添加完每页，再一起保存至文件中
    pdfFileWriter.write(open(out_file, 'wb'))


if __name__ == "__main__":
    if len(sys.argv) < 4:
       print("Usage: %s in_file out_file start_page end_page" % sys.argv[0])
       sys.exit()

    in_file = sys.argv[1]
    out_file = sys.argv[2]
    start_page = int(sys.argv[3])
    end_page = int(sys.argv[4])

    split_pdf(in_file, out_file, start_page, end_page)

